package org.jeecg.modules.exPingbiao.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.exPingbiao.domain.form.ExPingbiaoExpertRejectForm;
import org.jeecg.modules.exPingbiao.domain.vo.ExpertRecommendConfigVO;
import org.jeecg.modules.exPingbiao.entity.ExPingbiaoExpert;
import org.jeecg.modules.exPingbiao.entity.ExPingbiaoExpertDetail;
import org.jeecg.modules.exPingbiao.service.IExPingbiaoExpertDetailService;
import org.jeecg.modules.exPingbiao.service.IExPingbiaoExpertRecommendService;
import org.jeecg.modules.exPingbiao.service.IExPingbiaoExpertService;
import org.jeecg.modules.exPingbiao.service.IExPingbiaoSectionExpertConfigService;
import org.jeecg.modules.exPingbiao.vo.*;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Description: 评标
 * @Author: jeecg-boot
 * @Date: 2024-11-09
 * @Version: V1.0
 */
@Api(tags = "评标")
@RestController
@RequestMapping("/exPingbiao/exPingbiaoExpert")
@Slf4j
public class ExPingbiaoExpertController {
    @Autowired
    private IExPingbiaoExpertService exPingbiaoExpertService;
    @Autowired
    private IExPingbiaoExpertDetailService exPingbiaoExpertDetailService;
    @Autowired
    private IExPingbiaoExpertRecommendService expertRecommendService;
    @Autowired
    private IExPingbiaoSectionExpertConfigService expertConfigService;

    /**
     * 分页列表查询
     *
     * @param exPingbiaoExpert
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "评标-分页列表查询")
    @ApiOperation(value = "评标-分页列表查询", notes = "评标-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<ExPingbiaoExpert>> queryPageList(ExPingbiaoExpert exPingbiaoExpert,
                                                         @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                         HttpServletRequest req) {
        QueryWrapper<ExPingbiaoExpert> queryWrapper = QueryGenerator.initQueryWrapper(exPingbiaoExpert, req.getParameterMap());
        Page<ExPingbiaoExpert> page = new Page<ExPingbiaoExpert>(pageNo, pageSize);
        IPage<ExPingbiaoExpert> pageList = exPingbiaoExpertService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param exPingbiaoExpertPage
     * @return
     */
    @AutoLog(value = "评标-添加")
    @ApiOperation(value = "评标-添加", notes = "评标-添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody ExPingbiaoExpertPage exPingbiaoExpertPage) {
        ExPingbiaoExpert exPingbiaoExpert = new ExPingbiaoExpert();
        BeanUtils.copyProperties(exPingbiaoExpertPage, exPingbiaoExpert);
        exPingbiaoExpertService.saveMain(exPingbiaoExpert, exPingbiaoExpertPage.getExPingbiaoExpertDetailList());
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param exPingbiaoExpertPage
     * @return
     */
    @AutoLog(value = "评标-编辑")
    @ApiOperation(value = "评标-编辑", notes = "评标-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody ExPingbiaoExpertPage exPingbiaoExpertPage) {
        ExPingbiaoExpert exPingbiaoExpert = new ExPingbiaoExpert();
        BeanUtils.copyProperties(exPingbiaoExpertPage, exPingbiaoExpert);
        ExPingbiaoExpert exPingbiaoExpertEntity = exPingbiaoExpertService.getById(exPingbiaoExpert.getId());
        if (exPingbiaoExpertEntity == null) {
            return Result.error("未找到对应数据");
        }
        exPingbiaoExpertService.updateMain(exPingbiaoExpert, exPingbiaoExpertPage.getExPingbiaoExpertDetailList());
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "评标-通过id删除")
    @ApiOperation(value = "评标-通过id删除", notes = "评标-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        exPingbiaoExpertService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "评标-批量删除")
    @ApiOperation(value = "评标-批量删除", notes = "评标-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.exPingbiaoExpertService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "评标-通过id查询")
    @ApiOperation(value = "评标-通过id查询", notes = "评标-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<ExPingbiaoExpert> queryById(@RequestParam(name = "id", required = true) String id) {
        ExPingbiaoExpert exPingbiaoExpert = exPingbiaoExpertService.getById(id);
        if (exPingbiaoExpert == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(exPingbiaoExpert);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "评标明细通过主表ID查询")
    @ApiOperation(value = "评标明细主表ID查询", notes = "评标明细-通主表ID查询")
    @GetMapping(value = "/queryExPingbiaoExpertDetailByMainId")
    public Result<List<ExPingbiaoExpertDetail>> queryExPingbiaoExpertDetailListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<ExPingbiaoExpertDetail> exPingbiaoExpertDetailList = exPingbiaoExpertDetailService.selectByMainId(id);
        return Result.OK(exPingbiaoExpertDetailList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param exPingbiaoExpert
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ExPingbiaoExpert exPingbiaoExpert) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<ExPingbiaoExpert> queryWrapper = QueryGenerator.initQueryWrapper(exPingbiaoExpert, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //配置选中数据查询条件
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            queryWrapper.in("id", selectionList);
        }
        //Step.2 获取导出数据
        List<ExPingbiaoExpert> exPingbiaoExpertList = exPingbiaoExpertService.list(queryWrapper);

        // Step.3 组装pageList
        List<ExPingbiaoExpertPage> pageList = new ArrayList<ExPingbiaoExpertPage>();
        for (ExPingbiaoExpert main : exPingbiaoExpertList) {
            ExPingbiaoExpertPage vo = new ExPingbiaoExpertPage();
            BeanUtils.copyProperties(main, vo);
            List<ExPingbiaoExpertDetail> exPingbiaoExpertDetailList = exPingbiaoExpertDetailService.selectByMainId(main.getId());
            vo.setExPingbiaoExpertDetailList(exPingbiaoExpertDetailList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "评标列表");
        mv.addObject(NormalExcelConstants.CLASS, ExPingbiaoExpertPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("评标数据", "导出人:" + sysUser.getRealname(), "评标"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<ExPingbiaoExpertPage> list = ExcelImportUtil.importExcel(file.getInputStream(), ExPingbiaoExpertPage.class, params);
                for (ExPingbiaoExpertPage page : list) {
                    ExPingbiaoExpert po = new ExPingbiaoExpert();
                    BeanUtils.copyProperties(page, po);
                    exPingbiaoExpertService.saveMain(po, page.getExPingbiaoExpertDetailList());
                }
                return Result.OK("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.OK("文件导入失败！");
    }

    @AutoLog(value = "评标-添加")
    @ApiOperation(value = "评标-添加", notes = "评标-添加")
    @PostMapping(value = "/save")
    public Result<String> save(@RequestBody ExPingbiaoExpertParam exPingbiaoExpertParam) {
        if (exPingbiaoExpertParam == null || CollectionUtil.isEmpty(exPingbiaoExpertParam.getDetailList())) {
            return Result.error("参数有误");
        }
        exPingbiaoExpertService.save(exPingbiaoExpertParam);
        return Result.OK("操作成功！");
    }

    @ApiOperation(value = "评标-通过id查询", notes = "评标-通过id查询")
    @GetMapping(value = "/getInfo")
    public Result<ExPingbiaoExpertPage> getInfo(@RequestParam(name = "tenderListId", required = true) String tenderListId,
                                                @RequestParam(name = "businessType", required = true) String businessType,
                                                @RequestParam(name = "businessId", required = true) String businessId) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        return Result.OK(exPingbiaoExpertService.getInfo(tenderListId, businessType, businessId, sysUser.getId()));

    }

    @ApiOperation(value = "评标-通过id查询评标明细", notes = "评标-通过id查询")
    @GetMapping(value = "/getItemList")
    public Result<ExPingbiaoExpertItemDetailVO> getItemList(@RequestParam(name = "tenderListId", required = true) String tenderListId,
                                                            @RequestParam(name = "businessType", required = true) String businessType,
                                                            @RequestParam(name = "businessId", required = true) String businessId) {
        return Result.OK(exPingbiaoExpertService.getItemList(tenderListId, businessType, businessId));

    }

    @ApiOperation(value = "评标-组长点击前往下一步", notes = "评标-组长点击前往下一步")
    @GetMapping(value = "/nextBusiness")
    public Result<String> nextBusiness(@RequestParam(name = "bidSectionId", required = true) String bidSectionId) {
        return exPingbiaoExpertService.nextBusiness(bidSectionId);

    }

    @ApiOperation(value = "评标-组长回退", notes = "评标-组长回退")
    @PostMapping(value = "/backEdit")
    public Result<String> backEdit(@RequestBody @Valid ExPingbiaoExpertRejectForm form) {
        return exPingbiaoExpertService.backEdit(form);

    }

    @ApiOperation(value = "评标-查询评标配置项", notes = "评标-组长回退")
    @GetMapping(value = "/config")
    public Result<ExPingbiaoExpertConfigVO> config(@RequestParam(required = false) String projectId, @RequestParam(required = false) String sectionId) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        return exPingbiaoExpertService.config(projectId, sectionId, sysUser.getId());

    }

    @ApiOperation(value = "评标-查询专家评标记录", notes = "评标-查询专家评标记录")
    @GetMapping(value = "/queryRecord")
    public Result<List<ExPingbiaoExpertRecordVO>> queryRecord(String sectionId,String tenderListId) {
        return exPingbiaoExpertService.queryRecord(sectionId,tenderListId);
    }

    @ApiOperation("查询评分标准列表")
    @GetMapping(value = "/queyrPfbzRecordList")
    public Result<List<ExPingbiaoExpertDetail>> queyrPfbzRecordList(@RequestParam(name = "scoreStandardId") String scoreStandardId, @RequestParam(name = "standardType") String standardType, @RequestParam("sectionId") String expertId) {
        return exPingbiaoExpertService.queyrPfbzRecordList(null, expertId, scoreStandardId, standardType);
    }

    @ApiOperation("查询签到状态")
    @GetMapping(value = "/querySignInfo")
    public Result<Boolean> querySignInfo(@RequestParam("sectionId") String sectionId) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        return Result.ok(expertConfigService.selectSignInfoByUserId(sysUser.getId(), sectionId));
    }

    @ApiOperation("签到")
    @GetMapping(value = "/sign")
    public Result<String> sign(@RequestParam("sectionId") String sectionId) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        return expertConfigService.sign(sysUser.getId(), sectionId);
    }

    @ApiOperation("设置推荐专家")
    @GetMapping(value = "/setRecommend")
    public Result<String> setRecommendExpert(@RequestParam(name = "recommendExpertId") String recommendExpertId, @RequestParam("sectionId") String sectionId) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        return expertRecommendService.setRecommendExpert(sysUser.getId(), recommendExpertId, sectionId);
    }

    @ApiOperation("查询专家列表评审记录")
    @GetMapping(value = "/expertList")
    public Result<List<ExPingbiaoExpertRecommendVO>> queryExpertList(@RequestParam(name = "sectionId") String sectionId) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        return expertConfigService.queryRecommendExpertList(sysUser.getId(), sectionId);
    }

    @ApiOperation("查询专家推荐列表")
    @GetMapping(value = "/recommendInfo")
    public Result<ExpertRecommendConfigVO> recommendInfo(@RequestParam(name = "sectionId") String sectionId) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        return expertConfigService.gqueryExpertRecommendConfig(sysUser.getId(), sectionId);
    }

    @ApiOperation(value = "评标-完成全部评标", notes = "评标-全部完成")
    @GetMapping(value = "/complete")
    public Result<Boolean> complete(@RequestParam(required = false) String bidSectionId) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        return exPingbiaoExpertService.complete(bidSectionId, sysUser.getId());
    }

    // 已经合并至config 接口
//    @ApiOperation(value = "评标-获取完成状态", notes = "评标-全部完成")
//    @GetMapping(value = "/getAllCmpleted")
//    public Result<Boolean> getAllCmpleted(@RequestParam(required = false) String bidSectionId) {
//        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//        return  Result.ok(exPingbiaoExpertService.getAllCmpleted(bidSectionId, sysUser.getId()));
//    }

    @ApiOperation("查询专家列表")
    @GetMapping(value = "/queryExpertListBySectionId")
    public Result<List<ExPingbiaoExpertVO>> queryExpertListBySectionId(@RequestParam(name = "sectionId") String sectionId) {
        return expertConfigService.queryExpertList(sectionId);
    }

    @ApiOperation(value = "评标-根据专家ID以及投标信息查询专家评标记录", notes = "评标-根据专家ID以及投标信息查询专家评标记录")
    @GetMapping(value = "/getPingbiaoRecordListByExpertId")
    public Result<List<ExPingbiaoExpertDetail>> getPingbiaoRecordListByExpertId(String tenderListId,
                                                                                String businessType,
                                                                                String businessId, String expertId) {
        ExPingbiaoExpertPage  exPingbiaoExpertPage = exPingbiaoExpertService.getInfo(tenderListId, businessType, businessId, expertId);
        if(null == exPingbiaoExpertPage){
            return Result.ok(Lists.newArrayList());
        }
        return Result.OK(exPingbiaoExpertPage.getExPingbiaoExpertDetailList());

    }
}
